import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:message_tools/application.dart';
import 'package:message_tools/components/index.dart';
import 'package:message_tools/model/sms_template.dart';
import 'package:message_tools/store/index.dart';
import 'package:message_tools/store/view_model/sms_template_model.dart';
import 'package:message_tools/utils/date_utils.dart';

const buttonHeight = 50.0;
const rightButtonHeight = 40.0;

/// ListView 默认的实例,无状态
class AddSmsTemplatePage extends StatefulWidget {
  @override
  _AddSmsTemplatePageState createState() => _AddSmsTemplatePageState();
}

class _AddSmsTemplatePageState extends State<AddSmsTemplatePage> {
  TextEditingController _editCtrl = new TextEditingController();
  TextEditingController _titleCtrl = new TextEditingController();

  FocusNode _contentFocusNode = FocusNode();
  String _preMessage = "";
  int _wordCount = 0;
  int _messageCount = 0;
  Color _messageCountLabelColor = Colors.black;
  BuildContext _context;
  SmsTemplate _smsTemplate;
  String data;

  void initData() async {
    var json = await Application.getString("edit_sms_template");
    debugPrint("initData ====== json $json \n");

    if (json == null || json == "") {
      return;
    }

    setState(() {
      var map = Application.jsonDecode(json);
      _smsTemplate = SmsTemplate.fromJsonMap(map);
      _titleCtrl.text = _smsTemplate.title;
      _editCtrl.text = _smsTemplate.content;
      computePreMessage();
    });
  }

  @override
  void dispose() {
    _editCtrl.dispose();
    super.dispose();
  }

  @override
  void initState() {
    initData();
    _editCtrl.addListener(() {
      setState(() {
        computePreMessage();
      });
    });

    super.initState();
  }

  void computePreMessage() {
    _preMessage =
        _editCtrl.text.replaceAll("{|t|}", DateUtil.formatNowTime("HH:mm"));
    _preMessage =
        _preMessage.replaceAll("{|d|}", DateUtil.formatNowTime("yyyy-MM-dd"));
    while (true) {
      if (_preMessage.indexOf("{|n|}") < 0) {
        break;
      }

      int random = Random().nextInt(9);
      _preMessage = _preMessage.replaceFirst("{|n|}", random.toString());
    }

    computeWordCount();
  }

  Widget build(BuildContext context) {
    _context = context;

    return Scaffold(
      appBar: AppBarPlugin.Create("新增短信模板", centerTitle: true,
          leading: Builder(builder: (BuildContext c) {
        return IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            });
      })),
      body: Theme.of(context).platform == TargetPlatform.iOS
          ? CupertinoScrollbar(
              child: _buildBody(),
            )
          : Scrollbar(
              child: _buildBody(),
            ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
        child: Column(
      children: <Widget>[
        createNotice(),
        createTitleView(),
        Container(
            child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            createSmsMessageTextArea(),
            createDatetimeButtons(),
          ],
        )),
        createExtendsFieldButtons(),
        createSubmitButton(),
        createPreviewMessage(),
      ],
    ));
  }

  computeWordCount() {
    var tCount = getWordCount("{|t|}");
    var dCount = getWordCount("{|d|}");
    var nCount = getWordCount("{|n|}");
    var e1Count = getWordCount("{|e1|}");
    var e2Count = getWordCount("{|e2|}");
    var e3Count = getWordCount("{|e3|}");

    var content = _editCtrl.text;
    content = content.replaceAll("{|t|}", "");
    content = content.replaceAll("{|d|}", "");
    content = content.replaceAll("{|n|}", "");
    content = content.replaceAll("{|e1|}", "");
    content = content.replaceAll("{|e2|}", "");
    content = content.replaceAll("{|e3|}", "");

    int count = ((content.length +
        tCount * 5 +
        dCount * 11 +
        nCount * 1 +
        e1Count * 3 +
        e2Count * 3 +
        e3Count * 3));

    _wordCount = count * 2;
    _messageCount = (_wordCount.toDouble() / 140.0).ceil();
    _messageCountLabelColor = _wordCount > 140 ? Colors.red : Colors.black;
  }

  int getWordCount(String word) {
    var content = _editCtrl.text;

    int count = 0;
    while (true) {
      if (content.indexOf(word) < 0) {
        break;
      }

      content = content.replaceFirst(word, "");
      count++;
    }

    return count;
  }

  Container createNotice() {
    return Container(
        height: 40,
        padding: const EdgeInsets.all(5),
        child: Row(
          children: <Widget>[
            Expanded(
                flex: 1,
                child: Text("新增模板", style: new TextStyle(fontSize: 16))),
            Expanded(
              flex: 2,
              child: Text.rich(
                TextSpan(children: [
                  TextSpan(
                      text: '${_wordCount}',
                      style: TextStyle(
                          fontSize: 16.0, color: _messageCountLabelColor)),
                  TextSpan(
                      text: '/140 (共${_messageCount}条)',
                      style: TextStyle(
                        fontSize: 16.0,
                      )),
                ]),
              ),
            ),
            Expanded(flex: 1, child: Text("")),
          ],
        ));
  }

  Container createTitleView() {
    return Container(
        height: 40,
        padding: const EdgeInsets.all(5),
        child: Row(
          children: <Widget>[
            Expanded(
              child: TextField(
                controller: _titleCtrl,
                decoration: new InputDecoration(
                  hintText: "请输入模板名称",
                ),
              ),
            )
          ],
        ));
  }

  Expanded createSmsMessageTextArea() {
    return Expanded(
        flex: 3,
        child: new Container(
          margin: const EdgeInsets.only(left: 5, top: 5),
          padding: const EdgeInsets.only(left: 5),
          decoration: new BoxDecoration(
            //背景
            color: Colors.white,
            //设置四周边框
            border: createBorder(),
          ),
          child: TextField(
            maxLines: 8,
            autofocus: true,
            focusNode: _contentFocusNode,
            decoration: InputDecoration.collapsed(hintText: "请输入模板内容"),
            controller: _editCtrl,
            onChanged: (val) {},
          ),
        ));
  }

  Expanded createDatetimeButtons() {
    return Expanded(
        flex: 1,
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, //子组件的在交叉轴的对齐方式为起点
            children: <Widget>[
              Container(
                alignment: Alignment.topCenter,
                padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
                child: createButton(
                    height: rightButtonHeight,
                    text: "时间",
                    backgroundColor: Colors.blueGrey,
                    onPressed: () {
                      insertText("t");
                    }),
              ),
              Container(
                alignment: Alignment.topCenter,
                padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
                child: createButton(
                    height: rightButtonHeight,
                    text: "日期",
                    backgroundColor: Colors.blueGrey,
                    onPressed: () {
                      insertText("d");
                    }),
              ),
              Container(
                alignment: Alignment.topCenter,
                padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
                child: createButton(
                    height: rightButtonHeight,
                    text: "数字",
                    backgroundColor: Colors.blueGrey,
                    onPressed: () {
                      insertText("n");
                    }),
              ),
            ]));
  }

  Row createExtendsFieldButtons() {
    return Row(children: <Widget>[
      Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5),
        alignment: Alignment.center,
        child: createButton(
            height: buttonHeight,
            text: "扩展字段1",
            minWidth: double.infinity,
            backgroundColor: Colors.deepOrangeAccent,
            onPressed: () {
              insertText("e1");
            }),
      )),
      Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
        alignment: Alignment.center,
        child: createButton(
            height: buttonHeight,
            text: "扩展字段2",
            minWidth: double.infinity,
            backgroundColor: Colors.deepOrangeAccent,
            onPressed: () {
              insertText("e2");
            }),
      )),
      Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
        alignment: Alignment.center,
        child: createButton(
            height: buttonHeight,
            text: "扩展字段3",
            minWidth: double.infinity,
            backgroundColor: Colors.deepOrangeAccent,
            onPressed: () {
              insertText("e3");
            }),
      )),
    ]);
  }

  Row createSubmitButton() {
    return Row(
      children: <Widget>[
        Expanded(
            child: Container(
          padding: const EdgeInsets.only(left: 5, top: 5),
          alignment: Alignment.center,
          child: createButton(
              height: buttonHeight,
              text: "预览结果",
              minWidth: double.infinity,
              backgroundColor: Colors.blue,
              onPressed: () {
                var title = _titleCtrl.text.trim();
                var content = _editCtrl.text.trim();
                if (!validatorForm(title, content)) {
                  return;
                }

                _contentFocusNode.unfocus();
              }),
        )),
        Expanded(
          child: Container(
              padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
              alignment: Alignment.center,
              child: createButton(
                  height: buttonHeight,
                  text: "保存模板",
                  minWidth: double.infinity,
                  backgroundColor: Colors.green,
                  onPressed: () async {
                    var title = _titleCtrl.text.trim();
                    var content = _editCtrl.text.trim();
                    if (!validatorForm(title, content)) {
                      return;
                    }

                    _contentFocusNode.unfocus();

                    if (_smsTemplate == null) {
                      _smsTemplate = SmsTemplate();
                    }

                    _smsTemplate.title = title;
                    _smsTemplate.content = content;
                    _smsTemplate.createdAt =
                        DateUtil.formatNowTime("yyyy-MM-dd HH:mm");

                    Store.value<SmsTemplateModel>(context).save(_smsTemplate);
                    Navigator.pop(_context);
                  })),
        )
      ],
    );
  }

  bool validatorForm(String title, String content) {
    if (title.length == 0) {
      mAlertDialog(_context, "模板名称不能为空!");
      return false;
    }

    if (content.length == 0) {
      mAlertDialog(_context, "模板内容不能为空!");
      return false;
    }

    return true;
  }

  Container createPreviewMessage() {
    return Container(
        //margin: new EdgeInsets.all(5),
        width: double.infinity,
        padding: new EdgeInsets.all(40),
        decoration: new BoxDecoration(
            /*color: Color(0xFFebebf3),
                borderRadius: new BorderRadius.circular(10.0)),*/
            image: DecorationImage(
          image: AssetImage("assets/images/sms_bg.png"),
          fit: BoxFit.fill,
        )),
        child: new LimitedBox(
          maxWidth: MediaQuery.of(context).size.width,
          child: Text(_preMessage,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              maxLines: 100,
              textAlign: TextAlign.left,
              style: new TextStyle(height: 1, fontSize: 20)),
        ));
  }

  void insertText(String text) {
    var offset = _editCtrl.selection.start;

    var content = _editCtrl.text;
    if (content.trim().length == 0) {
      offset = 0;
      content = "{|$text|}";
    } else {
      var startStr = content.substring(0, offset);
      var endStr = content.substring(offset, content.length);

      content = "$startStr{|$text|}$endStr";
    }

    var currentOffset = offset + "{|$text|}".length;
    var newValue = _editCtrl.value.copyWith(
      text: content,
      selection: TextSelection.collapsed(
        offset: currentOffset, //offset to Last Character
      ),
      composing: TextRange.empty,
    );

    _editCtrl.value = newValue;
  }

  void mAlertDialog(BuildContext context, String content) {
    showDialog(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('系统提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
          elevation: 20,
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }
}
